package com.xxgc.eow.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaIgnore;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dtflys.forest.annotation.Get;
import com.dtflys.forest.annotation.Post;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.xxgc.eow.entity.Articletitle;
import com.xxgc.eow.entity.Choosetopic;
import com.xxgc.eow.service.IChoosetopicService;
import com.xxgc.eow.service.ITitleService;
import com.xxgc.eow.service.impl.TitleServiceImpl;
import com.xxgc.eow.utils.CosFile;
import com.xxgc.eow.utils.CosUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import com.xxgc.eow.result.Result;

import java.io.File;
import java.io.IOException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.xxgc.eow.service.IArticleService;
import com.xxgc.eow.entity.Article;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * <p>
 * 发表文章 前端控制器
 * </p>
 *
 * @author Mr.Abel
 * @since 2023-05-21
 */
@Tag(name = "发表文章")
@RestController
@RequestMapping("/article")
public class ArticleController {

    @Resource
    private IArticleService articleService;

    /**
     * 查询所有接口
     * @return
     */
    @ApiOperationSupport(author = "Mr.Abel")
    @Operation(summary = "查询所有接口", description = "查询发表文章所有数据")
    @SaIgnore
    @GetMapping
    public Result<List<Article>> findAll() {
        return Result.ok(articleService.selectAll());
    }

    /**
     * 根据id查询数据接口
     * @param id
     * @return
     */
    @ApiOperationSupport(author = "Mr.Abel")
    @Operation(summary = "根据id查询数据接口", description = "通过组件id查询")
    @Parameters({
            @Parameter(name = "id",description = "组件id",required = true,in=ParameterIn.QUERY)
    })
    @SaIgnore
    @GetMapping("/{id}")
    public Result<Article> findOne(@PathVariable Integer id) {
        return Result.ok(articleService.getById(id));
    }

    /**
     * 分页查询接口
     * @param pageNum
     * @param pageSize
     * @return
     */
    @ApiOperationSupport(author = "Mr.Abel")
    @Operation(summary = "分页查询接口", description = "分页查询")
    @Parameters({
            @Parameter(name = "pageNum",description = "页码",example="1",required = true,in=ParameterIn.QUERY),
            @Parameter(name = "pageSize",description = "每页多少条",example="10",required = true,in=ParameterIn.QUERY)
    })
    @SaCheckLogin
    @GetMapping("/page")
    public Result<Page<Article>> findPage(@RequestParam Integer pageNum,@RequestParam Integer pageSize) {
        QueryWrapper<Article> queryWrapper = new QueryWrapper<>();
        return Result.ok(articleService.page(new Page<>(pageNum, pageSize), queryWrapper));
    }

    /**
     * 新增和更新接口
     * @param
     * @return
     */
    @ApiOperationSupport(author = "Mr.Abel")
    @Operation(summary = "新增和更新接口", description = "传入id为更新,不传为新增,时间和有效字段均不填")
    @SaCheckLogin
    @PostMapping
    @SaIgnore
    public Result save(@RequestBody Article article) {
        articleService.saveOrUpdate(article);
        return Result.ok();
    }
    /**
     *
     * @param
     * @return
     */
    @ApiOperationSupport(author = "Mr.Abel")
    @Operation(summary = "上传图片接口", description = "上传头像接口")
    @SaIgnore
    @PostMapping("addImg")
    public Result addimg(@RequestBody MultipartFile myFile) throws IOException {
//        String headUrl = System.currentTimeMillis() + myFile.getOriginalFilename().substring(myFile.getOriginalFilename().indexOf("."));
//        File file = new File(headUrl);
//        FileUtils.copyInputStreamToFile(myFile.getInputStream(), file);
//        CosFile.upload("/images/article/" + headUrl, file);
//        String url = file.getName().substring(0,file.getName().indexOf("."));
//        if (file.exists()) {
//            file.delete();
//        }
        String url = CosUtils.uploadFile(myFile,"/images/article/");
        return Result.ok(url);
    }
    /**
     * 删除接口
     * @param id
     * @return
     */
    @ApiOperationSupport(author = "Mr.Abel")
    @Operation(summary = "删除接口", description = "通过id删除")
    @Parameters({
            @Parameter(name = "id",description = "组件id",required = true,in=ParameterIn.QUERY)
    })
    @SaIgnore
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        articleService.removeById(id);
        return Result.ok();
    }

    /**
     * 批量删除接口
     * @param ids
     * @return
     */
    @ApiOperationSupport(author = "Mr.Abel")
    @Operation(summary = "批量删除接口", description = "批量删除接口")
    @SaIgnore
    @PostMapping("/del/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        articleService.removeByIds(ids);
        return Result.ok();
    }

    @ApiOperationSupport(author = "Mr.Duan")
    @Operation(summary = "查询接口", description = "查询接口")
    @SaIgnore
    @GetMapping("/selectArticle")
    public Result<List<Article>> select(
            @RequestParam(defaultValue = "1") int PageNum,
            @RequestParam(defaultValue = "10") int PageSize){
        List<Article> a = articleService.selectPage(PageNum,PageSize);
        for (int i = 0; i < a.size(); i++) {
            List<String> articles = new ArrayList<>();
            List<Article> titleNames = articleService.selectTitleName(a.get(i).getArticleId());
            for (int j = 0; j < titleNames.size(); j++) {
                articles.add(titleNames.get(j).getTitleName());
            }
            a.get(i).setTitleNames(articles);
        }
        return Result.ok(a);

    }


    @ApiOperationSupport(author = "Mr.Duan")
    @Operation(summary = "查询动态封面接口", description = "查询动态封面接口")
    @GetMapping("/selectArticleSmall")
    @SaIgnore
    public Result selectCar(){
        List<Article> a = articleService.selectAll();
        String img;
        for (int i = 0; i < a.size(); i++) {
            List<String> articles = new ArrayList<>();
            List<Article> titleNames = articleService.selectTitleName(a.get(i).getArticleId());
            for (int j = 0; j < titleNames.size(); j++) {
                articles.add(titleNames.get(j).getTitleName());
            }
            if(StringUtils.substringBetween(a.get(i).getArticleContent(), "<img", ">")!=null){
                img = StringUtils.substringBetween(a.get(i).getArticleContent(), "<img src="+'"', '"'+">");
                a.get(i).setCoverImage(img);
            }else{
                a.get(i).setCoverImage(null);
            }
            a.get(i).setTitleNames(articles);
        }
        return new Result<>(200,"查询成功",a);
    }

    @ApiOperationSupport(author = "Mr.Duan")
    @Operation(summary = "添加文章接口", description = "添加文章接口")
    @PostMapping("/insertArticle")
    @SaIgnore
    public  Result insertArticle(@RequestBody Article article){
        Date date = new Date();
        Instant instant = date.toInstant();
        ZoneId zoneId = ZoneId.systemDefault();
        LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();
        article.setCreateTime(localDateTime);
        if (articleService.insertArticle(article)==1){
            return new Result<>(200,"添加成功");
        }else{
            return new Result<>(400,"添加失败添加数据可能错误咯！");
        }
    }


    @ApiOperationSupport(author = "Mr.Duan")
    @Operation(summary = "查询文章具体标题接口", description = "查询文章具体标题接口")
    @GetMapping("/insertTitle")
    @SaIgnore
    public Result insertTitle(@RequestParam List<String> titleName){
        Integer[] titleId = new Integer[titleName.size()];
        System.out.println(titleName.size());
        for (int i = 0; i <titleName.size() ; i++) {
            String r = titleName.get(i).replace("[","");
            String r2 = r.replace("]","").replace(" ","").replace("\"","");
            Integer t = articleService.selectTitleId(r2);
            titleId[i]= t;
        }
        return Result.ok(titleId);
    }

    @ApiOperationSupport(author = "Mr.Duan")
    @Operation(summary = "模糊查询文章接口", description = "模糊查询文章接口")
    @PostMapping("/selectLike/{PageNum}/{PageSize}")
    @SaIgnore
    public Result selectLikeSecondary(@RequestBody Article article,
                             @PathVariable int PageNum,
                             @PathVariable int PageSize){
        return Result.ok(articleService.selectKikeTitle(article,PageSize,PageNum));
    }

    @ApiOperationSupport(author = "Mr.Duan")
    @Operation(summary = "模糊查询文章后台接口", description = "模糊查询文章后台接口")
    @PostMapping("/selectLike")
    @SaIgnore
    public Result selectLike(@RequestBody Article article,
                             @RequestParam(defaultValue = "1") int PageNum,
                             @RequestParam(defaultValue = "5") int PageSize){
        return Result.ok(articleService.selectKikeTitle(article,PageSize,PageNum));
    }

    @ApiOperationSupport(author = "Mr.Duan")
    @Operation(summary = "假删文章接口", description = "假删文章接口")
    @GetMapping("/delArticle")
    @SaIgnore
    public Result delArticle(@RequestParam int articleId){
        if (articleService.delArticle(articleId)==1){
            return Result.ok();
        }else{
            return Result.error("删除失败！");
        }
    }


    @ApiOperationSupport(author = "Mr.Duan")
    @Operation(summary = "通过文章内容查询文章id接口", description = "通过文章内容查询文章id接口")
    @PostMapping("/selectArticleId")
    @SaIgnore
    public Result selectArticleId(@RequestBody Article article){
        Integer r = articleService.selectArticleId(article);
        System.out.println(r);
        if (r==null){
            return Result.error("未查询到该文章！");
        }else{
            return Result.ok(r);
        }

    }

    @ApiOperationSupport(author = "Mr.Duan")
    @Operation(summary = "添加文章标题表接口", description = "添加文章标题表接口")
    @PostMapping("/insertArticleTitle")
    @SaIgnore
    public Result insertArticleTitle(@RequestBody Articletitle articletitle){
        return Result.ok(articleService.insertArticleTitle(articletitle));
    }


    @ApiOperationSupport(author = "Mr.Duan")
    @Operation(summary = "修改文章接口", description = "修改文章接口")
    @PostMapping("/updateArticle")
    @SaIgnore
    public Result updateArticle(@RequestBody Article article){
        int a = articleService.updateArticleAll(article);
        if (a==1){
            List<String> titleName = article.getTitleNames();
            int articleId = article.getArticleId();
            Integer[] titleId = new Integer[titleName.size()];
            //删除全部文章标题
            System.out.println(articleService.delArticleTitle(articleId)+"删除文章标题");
            for (int i = 0; i <titleName.size() ; i++) {
                String r = titleName.get(i).replace("[","");
                String r2 = r.replace("]","").replace(" ","").replace("\"","");
                Integer t = articleService.selectTitleId(r2);
                titleId[i]= t;
                System.out.println(t);


                //添加文章标题
                Articletitle articletitle = new Articletitle();
                articletitle.setArticleId(articleId);
                articletitle.setTitleId(t);
                System.out.println(articleService.insertArticleTitle(articletitle)+"添加文章标题");
            }

            return Result.ok("修改文章成功！");
        }else{
            return Result.error("修改文章失败！");
        }
    }

    @ApiOperationSupport(author = "Mr.Duan")
    @Operation(summary = "更具用户id查询文章接口", description = "更具用户id查询文章接口")
    @GetMapping("/selectByUserId")
    @SaIgnore
    public Result selectByUserId(@RequestParam int userId){
        return Result.ok(articleService.selectByUserId(userId));
    }
}